var canvas =  document.getElementById('canvas');
var context = canvas.getContext('2d');

var mouseDown = {};
var dragging;
var drawingSurfaceImageData;

function drawGrid(){
    context.beginPath();
    context.lineWidth = 1;
    context.strokeStyle='lightgray';
    for(var i=10 + 0.5; i < canvas.width;i += 10){
        context.moveTo(i,0);
        context.lineTo(i,400);
        context.stroke();
    }

    context.beginPath();
    for(var i=10 + 0.5; i < canvas.height;i += 10) {
        context.moveTo(0,i);
        context.lineTo(600,i);
        context.stroke();
    }
}

drawGrid();


function saveDrawingSurface(){
    drawingSurfaceImageData = context.getImageData(0,0,canvas.width,canvas.height);
}

function restoreDrawingSurface(){
    context.putImageData(drawingSurfaceImageData,0,0);
}

function windowToCanvas(x,y) {
    var box = canvas.getBoundingClientRect();

    return {
        x: x - box.left,
        y: y - box.top
    }
};

canvas.onmousedown = function(e){
    e.preventDefault();

    var loc =windowToCanvas(e.clientX, e.clientY);
    mouseDown.x = loc.x;
    mouseDown.y = loc.y;

    saveDrawingSurface();
    dragging = true;
};

canvas.onmousemove = function(e){
    if(!dragging){
        return;
    }

    restoreDrawingSurface();

    var loc =windowToCanvas(e.clientX, e.clientY);


    context.beginPath();
    context.moveTo(mouseDown.x, mouseDown.y);
    context.lineTo(loc.x, loc.y);
    context.strokeStyle = 'red';
    context.stroke();


};

canvas.onmouseup = function(e){
    dragging = false;
};



